package cn.com.header.zbpk.web;

import cn.com.header.core.support.web.springmvc.BaseController;
import cn.com.header.zbpk.account.service.IUserService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Objects;

/**
 * @author luohaidian
 * @date 2017-11-13
 * @time 15:32
 */
public class CommonController extends BaseController {

    /**
     * 当前登录用户的ID
     *
     * @return
     */
    protected Long getCurrentUserId() {
        IUserService.SecurityUser user = getCurrentUser();
        if (Objects.isNull(user)) {
            return null;
        }
        return user.getId();
    }

    /**
     * 获取当前用户
     *
     * @return
     */
    protected IUserService.SecurityUser getCurrentUser() {
        SecurityContext context = SecurityContextHolder.getContext();
        if (Objects.isNull(context)) {
            logger.info("当前用户未登录，或者登录超时");
            return null;
        }
        Authentication authentication = context.getAuthentication();
        if (Objects.isNull(authentication)) {
            logger.info("当前用户未登录，或者登录超时");
            return null;
        }
        Object principal = authentication.getPrincipal();
        if (Objects.isNull(principal)) {
            logger.info("当前用户未登录，或者登录超时");
            return null;
        }
        if (principal instanceof IUserService.SecurityUser) {
            return (IUserService.SecurityUser) principal;
        }
        return null;
    }

    /**
     * 判断用户是否登录
     *
     * @return
     */
    protected boolean checkUserLogined() {
        if (!Objects.isNull(getCurrentUser())) {
            return true;
        }
        return false;
    }

    /**
     * 每页默认记录数
     */
    protected final int pageSize = 10;

}
